'use strict'

const fs = require('fs');
const  router = require('koa-router')();

function getListPath(filePath){
   
    let filesPath = filePath || __dirname;
    
    let path = fs.readdirSync(filesPath);
    
    let tmp = path.filter(item =>{
        return item.endsWith('.js')&&item !=='index.js';
    })

    return tmp;
}

function resgin(router,tmp){
    
    tmp.forEach(item=>{
        let tmpPath = __dirname+'/'+item;
        let obj = require(tmpPath);

        for (let key in obj) {
            let tmpArr = key.split('');
            let tmpMethor = tmpArr[0];
            let tmpUrl = tmpArr[1];
            let tmpFunction = obj[key];

            if (tmpMethor ==='get') {
                router.get(tmpUrl,tmpFunction)
            }else if (tmpMethor==='post') {
                router.post(tmpUrl,tmpFunction)
            }else if (tmpMethor==='put') {
                router.put(tmpUrl,tmpFunction)
            }else if (tmpMethor==='delect') {
                router.delect(tmpUrl,tmpFunction)
            }
                         
        }
    })
    return router.routes();
}

module.exports = function(){
    let tmp = getListPath();
    let fn = resgin(router,tmp);
    return fn;
};